package imoocvideodev.controller.interceptor;

import imoocvideodev.common.result.IMoocJSONResult;
import imoocvideodev.common.util.JsonUtils;
import imoocvideodev.common.util.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * @Author: Redi
 * @Date: 2021/2/24 11:34
 * @Description: 小程序用户登录拦截器
 */
public class MiniInterceptor implements HandlerInterceptor {

    @Autowired
    public RedisOperator redis;
    public static final String USER_REDIS_SESSION = "user-redis-session";
    /**
     * 拦截请求，在controller调用之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("headerUserId");
        String userToken =request.getHeader("headerUserToken");
        if (StringUtils.isNoneBlank(userId,userToken)){
            String uniqueToken = redis.get(USER_REDIS_SESSION + ":" + userId);
            if(StringUtils.isBlank(uniqueToken) && StringUtils.isEmpty(uniqueToken)){
                System.out.println("uniqueToken为空,请登录...");
                returnErrorResponse(response,IMoocJSONResult.errorTokenMsg("请登录..."));
                return false;
            } else{
                if(!uniqueToken.equals(userToken)){
                    System.out.println("账号被挤出...");
                    returnErrorResponse(response,IMoocJSONResult.errorTokenMsg("账号被挤出..."));
                    return false;
                }
            }
        }else{
            System.out.println("userId或userToken为空,请登录...");
            returnErrorResponse(response,IMoocJSONResult.errorTokenMsg("请登录..."));
            return false;
        }
        /**
         * 返回 false：请求被拦截，返回
         * 返回 true ：请求OK，可以继续执行，放行
         */
        return true;
    }

    public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) throws IOException {
        OutputStream outputStream = null;
        try{
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            outputStream = response.getOutputStream();
            outputStream.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            outputStream.flush();
        }finally {
            if (outputStream != null){
                outputStream.close();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
